import { marked, type Renderer } from "marked"
import { markedHighlight } from "marked-highlight"
import hljs from "highlight.js"

// Configure marked with syntax highlighting
marked.use(
  markedHighlight({
    langPrefix: "hljs language-",
    highlight(code: string, lang: string | undefined): string {
      // Ensure code is a string
      const codeStr = typeof code === 'string' ? code : ''
      // Ensure lang is a string
      const langStr = typeof lang === 'string' ? lang : ''
      const language = hljs.getLanguage(langStr) ? langStr : "plaintext"
      return hljs.highlight(codeStr, { language }).value
    },
  }),
)

// Configure marked options
marked.setOptions({
  breaks: true,
  gfm: true,
})

// Custom renderer for better link and image handling
const renderer = new marked.Renderer()

// Custom link renderer - open external links in new tab
renderer.link = ({ href, title, tokens }: { href: string; title?: string | null; tokens: any[] }): string => {
  // Ensure href is a string before calling startsWith
  const hrefStr = typeof href === 'string' ? href : ''
  const isExternal = hrefStr && (hrefStr.startsWith("http://") || hrefStr.startsWith("https://"))
  const target = isExternal ? ' target="_blank" rel="noopener noreferrer"' : ""
  const titleAttr = title ? ` title="${title}"` : ""
  const text = tokens.map((token: any) => token.text).join('')
  return `<a href="${hrefStr}"${titleAttr}${target} class="text-primary hover:text-primary/80 underline underline-offset-4">${text}</a>`
}

// Custom image renderer - add responsive classes
renderer.image = ({ href, title, text }: { href: string; title: string | null; text?: string; tokens?: any[] }): string => {
  const hrefStr = typeof href === 'string' ? href : ''
  const titleAttr = title ? ` title="${title}"` : ""
  const altAttr = text ? ` alt="${text}"` : ""
  return `<img src="${hrefStr}"${altAttr}${titleAttr} class="rounded-lg shadow-md max-w-full h-auto mx-auto my-6" loading="lazy" />`
}

// Custom code block renderer
renderer.code = ({ text, lang, escaped }: { text: string; lang?: string; escaped?: boolean }): string => {
  // Ensure text is a string
  const codeStr = typeof text === 'string' ? text : ''
  // Ensure lang is a string
  const languageStr = typeof lang === 'string' ? lang : ''
  const validLanguage = languageStr && hljs.getLanguage(languageStr) ? languageStr : "plaintext"
  const highlighted = hljs.highlight(codeStr, { language: validLanguage }).value
  return `<pre class="bg-muted rounded-lg p-4 overflow-x-auto my-6"><code class="hljs language-${validLanguage}">${highlighted}</code></pre>`
}

// Custom blockquote renderer
renderer.blockquote = ({ tokens }: { tokens: any[] }): string => {
  const quote = tokens.map((token: any) => token.text).join('')
  return `<blockquote class="border-l-4 border-primary pl-4 py-2 my-6 italic text-muted-foreground bg-muted/50 rounded-r-lg">${quote}</blockquote>`
}

marked.use({ renderer })

export function parseMarkdown(markdown: string): string {
  // Preprocess Obsidian-style image links: ![[image.png]]
  let processedMarkdown = markdown.replace(/!\[\[([^\[\]]+)\]\]/g, (match, imagePath) => {
    // Trim whitespace and normalize path
    const trimmedPath = imagePath.trim();
    
    // Use /images/ directory in public folder
    const fullImagePath = `/images/${trimmedPath}`;
    
    // Return standard Markdown image syntax
    return `![${trimmedPath}](${fullImagePath})`;
  });
  
  // Force synchronous execution
  return marked.parse(processedMarkdown).toString();
}
